import LayVmodelBase from "./LayVmodelBase.js"
import { logger, tools, runtime } from "./tools.js";

/**Layui日期范围 */
class LayDateRangeVmodel extends LayVmodelBase {
    /**LayDate 配置 */
    config = null;

    constructor(elem, config) {
        super(elem);
        let element = this.element;
        this.config = config || {
            type: "date",
            range: true,
            format: "yyyy-MM-dd",
            done:null
        };
        this.config.range = true;
        var beginInput = $(element).find(".date-begin")[0] || $(element).find("input[type='text']")[0];
        var endInput = $(element).find(".date-end")[0] || $(element).find("input[type='text']")[1];
        if (!beginInput || !endInput) {
            throw new Error("laydateRange 必须包含两个input[type='text']");
        }
        this.beginInput = beginInput;
        this.endInput = endInput;
    }

    /**[override] */
    viewModelInit() {
        super.viewModelInit();
        this.vm.begin = ko.observable();
        this.vm.end = ko.observable();
    }

    init() {
        if(!super.init()) return;
        var tis = this;
        let vm = this.vm;
        var config = this.config;
        config.elem = this.element;
        config.range = [this.beginInput,this.endInput];

        let innerDone = config.done;
        let laydate = tools.laymod("laydate");
        config.done = function (value, date, endDate) {
            let format = config.format || "yyyy-MM-dd";
            let beginVal = laydate.parse(date, format);
            let endVal = laydate.parse(endDate, format);
            vm.begin(beginVal);
            vm.end(endVal);
            return innerDone && innerDone.call(this, ...arguments);
        }
        // 日期
        laydate.render(config);

        //订阅value变化
        vm.begin.subscribe((newValue) => {
            $(tis.beginInput).val(newValue);
        });
        vm.end.subscribe((newValue) => {
            $(tis.endInput).val(newValue);
        });

        $(this.beginInput).val(vm.begin());
        $(this.endInput).val(vm.end());

        this.inited = true;
    }

    onDisabledChange() {

    }
}

export default LayDateRangeVmodel;